import React, { Component } from 'react';
import { GLOBAL } from '../../../../config/global';
import { StyleSheet, Text, View, Image, TouchableOpacity, FlatList, Alert, TextInput } from "react-native";
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common.js';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import ToastUtil from '../../../../utils/toast';
import HTTP from '../../../../utils/http';
import { API, API_GENERATE } from '../../../../config/api';
import { Button } from '../../../../components/form/button';
import { NavigationEvents } from 'react-navigation';
const scale = GLOBAL.SCALE;
const checkOn = require('../../../../imgs/checkOn.png');
const checkOff = require('../../../../imgs/checkOff.png');


export class DictionaryPage extends Component {
	static navigationOptions = ({ navigation }) => {
		return {
			title: '结算公式',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerStyle: {
				elevation: 0,
				backgroundColor: style.color.themeColor,
			},
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	}

	constructor(props) {
		super(props);
		let {paramsData} = this.props.navigation.state.params||{};
		this.state = {
			status: 'data',
			listData: [],
			refreshIcon: false,
		};
		this.totalPage = 1;
		this.reload = true; // 判断是整个页面刷新还是下拉刷新

		this.pageParams = {
			pageNo: 1,
			pageSize: 15,
			formulaName: null,
			orderType:paramsData.orderType,
			goodsId:paramsData.goodsId
		}
		this.selectedFrame = {};
	}

	_changeData = (data) => {
		let removeIndex = -1;
		data.forEach((item, index) => {
			item.selected = this.selectedFrame.formulaId == item.formulaId;
			if (item.selected) removeIndex = index;
		})
		if (removeIndex >= 0) data.unshift(data.splice(removeIndex, 1)[0])
		return data;
	}

	initPage = async () => {
		this.setState({
			status: this.reload ? 'loading' : 'data',
			refreshIcon: !this.reload && this.pageParams.pageNo == '1'
		})
		let res = await HTTP.POST(API_GENERATE(API.GET_PRICE), this.pageParams);
		//if (this.pageParams.pageNo == '1') this.selectedFrame = {};
		if (res) {
			this.totalPage = res.totalPage;
			res = this._changeData(res);
			this.setState({
				status: res.length > 0 ? 'data' : 'empty',
				listData: this.pageParams.pageNo == '1' ? res : this.state.listData.concat(res),
				refreshIcon: false,
			}, () => {
				console.log('this.state.listData', this.state.listData)
			})
		} else {
			this.setState({
				refreshIcon: false,
				status: 'error'
			})
		}
	}

	// 下拉刷新当月变更计划
	refresh = () => {
		this.pageParams.pageNo = 1;
		this.reload = false;
		this.initPage();
	}

	// 刷新当月变更计划
	reloadPage = () => {
		this.pageParams.pageNo = 1;
		this.reload = true;
		this.initPage();
	}

	// 加载更多当月变更计划
	loadMore = () => {
		if (this.totalPage > this.pageParams.pageNo) {
			this.pageParams.pageNo++;
			this.reload = false;
			this.initPage();
		}
	}

	renderSearchWarp = () => {
		return (
			<View style={styles.searchWrap}>
				<TextInput
					ref="orderKeywordsInput"
					style={[styles.searchInput]}
					underlineColorAndroid='transparent'
					placeholder={"结算公式名称"}
					placeholderTextColor="rgba(39, 39, 39, .5)"
					maxLength={30}
					returnKeyType={'search'}
					defaultValue={this.pageParams.formulaName}
					onChangeText={(txt) => { this.pageParams.formulaName = txt; }}
					onSubmitEditing={() => { this.refresh() }}
				/>
			</View>
		)
	}

	selectFrame = (index) => {
		let { listData } = this.state;
		listData.forEach((item, i) => {
			if (index == i) {
				item.selected = !item.selected;
				this.selectedFrame = item.selected ? item : {}
			} else {
				item.selected = false;
			}
		})
		console.log('this.selectedFrame', this.selectedFrame)
		this.setState(listData)
	}

	nextStep = async () => {
		if (this.selectedFrame.formulaId) {
			this.jumpPage();
		} else {
			ToastUtil.showWarning('请选择结算公式');
		}
	}

	jumpPage = () => {
		this.props.navigation.state.params.getCallBack(this.selectedFrame);
		this.props.navigation.goBack();
	}

	renderListItem = (data) => {
		let item = data.item
		return (
			<View style={{ paddingLeft: 12 * scale, paddingRight: 12 * scale, }}>
				<TouchableOpacity activeOpacity={.6} style={{ marginBottom: 20 * scale, flexDirection: 'row', }} onPress={() => { this.selectFrame(data.index) }}>
					<Image style={{ marginRight: 8 * scale }} source={item.selected ? checkOn : checkOff} />
					<Text style={{ fontSize: 13 * scale, paddingRight: 20 * scale, lineHeight: 20 * scale }}>{item.formulaName || '--'}</Text>
				</TouchableOpacity >
			</View>
		)
	}

	render () {
		let { status, listData, refreshIcon } = this.state;
		return (
			<View style={styles.container}>
				<NavigationEvents
					onWillFocus={({ action }) => {
						let { priceFormlaId } = this.props.navigation.state.params || {};
						this.selectedFrame = { formulaId: priceFormlaId };
						this.initPage();
					}}
				/>
				{this.renderSearchWarp()}
				{
					status == 'data' ? (
						<View style={{ flex: 1 }}>
							<FlatList
								data={listData}
								renderItem={this.renderListItem}
								refreshing={refreshIcon}
								onRefresh={() => { this.refresh() }}
								onEndReachedThreshold={0.1}
								onEndReached={() => { this.loadMore() }}
							/>
						</View>
					) : null
				}
				{
					status == 'data' ? (
						<View style={styles.btnWarp}>
							<Button text={'添加'} width={300} height={34} onPress={() => { this.nextStep() }} />
						</View>
					) : null
				}


				{
					status != 'data' ? (<PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this.reloadPage} />) : null
				}
			</View>
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: '#F5F5F5'
	},
	searchWrap: {
		width: '100%',
		height: 66 * scale,
		flexDirection: 'row',
		justifyContent: 'space-around',
		alignItems: 'center',
	},
	searchInput: {
		borderWidth: 1,
		borderStyle: 'solid',
		borderRadius: 6 * scale,
		borderColor: '#EDEDED',
		backgroundColor: '#fff',
		textAlign: 'center',
		height: 36 * scale,
		width: 250 * scale,
		paddingLeft: 10 * scale,
		paddingRight: 10 * scale,
		paddingVertical: 0,
	},
	btnWarp: {
		height: 72 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-around',
	},
})